package com.tulele.vtool.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tulele.vtool.mapper.PageDetailLogMapper;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.CustomerMarqueeInfo;
import com.tulele.vtool.model.combinedEntity.LookUserArticleStatisInfo;
import com.tulele.vtool.model.logEntity.PageDetailLog;
import com.tulele.vtool.model.reqEntity.PurchaseVipServiceReqBean;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.*;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import com.tulele.vtool.utils.SysConstant;
import com.tulele.vtool.utils.ToolUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.xmlbeans.GDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
public class VipInfoHandler {

    @Autowired
    private IVipInfoService vipInfoService;

    @Autowired
    private IUserBargainActivityService userBargainActivityService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private ILookArticleInfoService lookArticleInfoService;

//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

    @Autowired
    private IBrandPromotionSettleInfoService brandPromotionSettleInfoService;

    @Autowired
    private IBrandPromotionPayUserInfoService brandPromotionPayUserInfoService;

    /**
     * 优惠券前缀
     */
    private static final String COUPON_PRE = "ADD_COUPON_TIMELINESS:";

    /**
     * 客服赠送优惠券时效 单位：分钟
     */
    private static  final double COUPON_TIMELINESS = 10;


    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private PageDetailLogMapper pageDetailLogMapper;



    @PostMapping(value = "/getPlatformVipInfo", produces="application/json;charset=UTF-8")
    public RespData getPlatformVipInfo(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody(required=false) PurchaseVipServiceReqBean purchaseVipServiceReqBean) {

//        if(springProfilesActive.equals("dev")){
//            springProfilesActive="prodbst";
//        }

        List<VipPriceInfo> vipPriceInfoList = vipInfoService.getVipPriceInfo(springProfilesActive);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(6);

        double accountBalance = 0d;

        Double tempAccountBalance = userInfoService.getUserAccountBalance(Integer.parseInt(userId));
        if(tempAccountBalance != null && !"".equals(tempAccountBalance.toString().trim())) {
            accountBalance = tempAccountBalance.doubleValue();
        }

        List<Map<String, Object>> priceInfoList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(vipPriceInfoList)) {

            double finalAccountBalance = accountBalance;
            vipPriceInfoList.forEach(info -> {
                Map<String, Object> infoMap = Maps.newHashMapWithExpectedSize(9);

                infoMap.put("vipId", info.getId());
                infoMap.put("vipDes", info.getVipDesc());
                infoMap.put("originalVipPrice", info.getOriginalVipPrice());
                infoMap.put("vipPrice", info.getVipPrice());
                infoMap.put("vipExplain", info.getVipExplain());
                infoMap.put("coupon", info.getCoupon());
                infoMap.put("maxCommission", info.getMaxCommission());

                /**
                 * A:totalAmount 会员金额
                 * B:maxCommission 佣金最大抵扣金额
                 * C:accountBalance 佣金金额
                 *
                 * 1.C（佣金金额） >= B（佣金最大抵扣金额）
                 * 会员金额 = A - B
                 * 剩余佣金金额 = C - B
                 *
                 *
                 * 2.C（佣金金额） < B（佣金最大抵扣金额）
                 * 会员金额 = A - C
                 * 剩余佣金金额 = 0
                 **/

                //应付金额
                double totalAmount = info.getVipPrice();

                //剩余佣金金额
                double accountBalanceLast = finalAccountBalance;

                //查询佣金最大抵扣金额
                double maxCommission = info.getMaxCommission();

                if (finalAccountBalance >= maxCommission) {
                    //应付金额
                    totalAmount = totalAmount - maxCommission;

                    //剩余佣金金额
                    accountBalanceLast = finalAccountBalance - maxCommission;
                }else if(finalAccountBalance > 0){
                    //应付金额
                    totalAmount = totalAmount - finalAccountBalance;

                    //剩余佣金金额
                    accountBalanceLast = 0;
                }
                //应付金额
                infoMap.put("vipPriceLast", totalAmount);

                /**
                 *使用精确小数BigDecimal
                 */
                BigDecimal bg = new BigDecimal(accountBalanceLast);
                /**
                 * 参数：
                 newScale - 要返回的 BigDecimal 值的标度。
                 roundingMode - 要应用的舍入模式。
                 返回：
                 一个 BigDecimal，其标度为指定值，其非标度值可以通过此 BigDecimal 的非标度值乘以或除以十的适当次幂来确定。
                 */
                double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                //剩余佣金金额
                infoMap.put("accountBalanceLast", f1);

                priceInfoList.add(infoMap);
            });

        }

        // 佣金金额余额
        resultMap.put("accountBalance", accountBalance);
        resultMap.put("vipPriceInfo", priceInfoList);

        List<String> vipPrivilegeInfoList = Lists.newArrayList();
        vipPrivilegeInfoList.add("查看谁看了我的朋友圈文章");
        vipPrivilegeInfoList.add("添加文章不限次数");
        vipPrivilegeInfoList.add("可删除文章里的任何信息、广告");

        resultMap.put("vipPrivilegeInfo", vipPrivilegeInfoList);

        UserInfo userSubTimeRelationInfo = userInfoService.getUserSubTimeRelationInfo(Integer.parseInt(userId));
        if (userSubTimeRelationInfo != null) {

            //Date subscriberTime = userSubTimeRelationInfo.getSubscribeTime();
            Date subscriberTime = userSubTimeRelationInfo.getCreateTime();//20200421 hyl

            double couponRemainTime = 0d;

            long couponRemainTimeAsMinutes = 0;
            long couponRemainTimeAsSec = 0;
            long couponRemainTimeAsMil = 0;
            int vipStatus = Optional.ofNullable(userInfoService.getUserVipStatus(Integer.parseInt(userId))).orElse(0);

            //if (subscriberTime != null && vipStatus == 0) {  //20200827 会员也可以有优惠券
            if (subscriberTime != null) {

                couponRemainTime = (double)SysConstant.COUPON_VALID_TIME - DateUtil.getTimeDiff(3, subscriberTime);
                //优惠券剩余有效时间
                if (couponRemainTime < 0 || couponRemainTime > 26) {
                    // 20200429 yl 获取客服手动添加的优惠卷 start
                    Object cacheObject = redisCacheUtil.getCacheObject(VipInfoHandler.COUPON_PRE + userId);
                    if (null != cacheObject){
                        //以小时计算
                        UserInfo userInfo = JSONObject.parseObject((String) cacheObject, UserInfo.class);
                        double accuracyCouponRemainTime =  (VipInfoHandler.COUPON_TIMELINESS - DateUtil.getTimeDiff(2,userInfo.getCreateTime())) / 60;
                        couponRemainTime = Double.parseDouble(String.format("%.1f", accuracyCouponRemainTime)) < 0 ? 0 :Double.parseDouble(String.format("%.1f", accuracyCouponRemainTime));
                        // 以分钟及秒计算 10分钟倒计时
                        Duration duration = Duration.between(new Date().toInstant(), new Date(userInfo.getCreateTime().getTime()+600000).toInstant());
                        couponRemainTimeAsMinutes = duration.toMinutes();
                        couponRemainTimeAsSec = duration.getSeconds() - ( Duration.ofMinutes(duration.toMinutes()).getSeconds());
                        couponRemainTimeAsMil = duration.toMillis() - (couponRemainTimeAsMinutes * 60 * 1000) - (couponRemainTimeAsSec *1000);
                    }else {
                        couponRemainTime = 0;
                    }
                     // 20200429 yl 获取客服手动添加的优惠卷 end
                }

                if (couponRemainTime == 0) {

                    resultMap.put("couponStatus", 0);
                    resultMap.put("couponRemainTime", 0);
                    resultMap.put("couponAmount", 0);

                } else {

                    resultMap.put("couponStatus", 1);
                    resultMap.put("couponRemainTimeAsMinutes", couponRemainTimeAsMinutes <= 0 ? 0 :couponRemainTimeAsMinutes);
                    resultMap.put("couponRemainTimeAsSec", couponRemainTimeAsSec <= 0 ? 0 :couponRemainTimeAsSec);
                    resultMap.put("couponRemainTimeAsMil", couponRemainTimeAsMil <= 0 ? 0 :couponRemainTimeAsMil);
                    resultMap.put("couponRemainTime", couponRemainTime);
                    resultMap.put("couponAmount", priceInfoList.get(0).get("coupon"));

                }

                resultMap.put("couponRemainTime", couponRemainTime);
                resultMap.put("couponAmount", priceInfoList.get(0).get("coupon"));


                if(vipStatus == 0) {
                    try {
                        PageDetailLog pageDetailLog = new PageDetailLog();
                        pageDetailLog.setPageName("订单支付页");
                        pageDetailLog.setUserId(Integer.parseInt(userId));
                        pageDetailLog.setGzhCode(springProfilesActive);
                        pageDetailLog.setAccessTime(new Date());

                        if(purchaseVipServiceReqBean!=null && purchaseVipServiceReqBean.getMobileType()!=null){//20201215 hyl 添加用户点进来的 渠道
                            pageDetailLog.setMobileType(purchaseVipServiceReqBean.getMobileType());
                        }

                        pageDetailLogMapper.addPageAccess(pageDetailLog);
                    } catch (Exception e) {

                    }
                }

            } else {

                resultMap.put("couponStatus", 0);
                resultMap.put("couponRemainTime", 0);
                resultMap.put("couponAmount", 0);
            }
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getVipPurchaseInfo", produces="application/json;charset=UTF-8")
    public RespData getVipPurchaseInfo(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {

        List<VipPriceInfo> vipPriceInfoList = vipInfoService.getVipPriceInfo(springProfilesActive);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(4);

        List<Map<String, Object>> priceInfoList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(vipPriceInfoList)) {

            vipPriceInfoList.forEach(info -> {
                Map<String, Object> infoMap = Maps.newHashMapWithExpectedSize(4);
                infoMap.put("vipId", info.getId());
                infoMap.put("vipDes", info.getVipDesc());
                infoMap.put("originalVipPrice", info.getOriginalVipPrice());
                infoMap.put("vipPrice", info.getVipPrice());

                priceInfoList.add(infoMap);
            });

        }

        resultMap.put("vipPriceInfo", priceInfoList);

        List<String> vipPrivilegeInfoList = Lists.newArrayList();
        vipPrivilegeInfoList.add("查看谁看了我的朋友圈文章");
        vipPrivilegeInfoList.add("添加文章不限次数");
        vipPrivilegeInfoList.add("可删除文章里的任何信息、广告");

        resultMap.put("vipPrivilegeInfo", vipPrivilegeInfoList);

        //VIP砍价活动信息
        PlatformActivityInfo platformActivityInfo = userBargainActivityService.getPlatformBargainActivityInfo(1);
        if (platformActivityInfo != null && platformActivityInfo.getActStatus().intValue() == 1) {

            resultMap.put("bargainActivityStatus", 1);

        } else {

            resultMap.put("bargainActivityStatus", 0);

        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/getVipPageMarqueeInfo", produces="application/json;charset=UTF-8")
    public RespData getUserWithdrawMarqueeInfo(@RequestHeader("userId") String userId) {

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);

        List<CustomerMarqueeInfo> marqueeInfo = Lists.newArrayList();

        List<LookUserArticleStatisInfo> lookUserArticleStatisInfos = lookArticleInfoService.getLookUserArticleStatisInfo(Integer.parseInt(userId), 5);

        if (CollectionUtils.isNotEmpty(lookUserArticleStatisInfos) && lookUserArticleStatisInfos.size() > 0) {

            lookUserArticleStatisInfos.forEach(info -> {

                if (info != null) {

                    int totalLookCount = Optional.ofNullable(info.getTotalLookCount()).orElse(1) + 10;
                    int num = (int) Math.random() * 50 + 51;//50~100的随机数
                    Integer lookUserId = info.getUserId();

                    UserInfo lookUserInfo = userInfoService.getUserBaseInfo(lookUserId);
                    if (lookUserInfo != null) {
                        CustomerMarqueeInfo customerMarqueeInfo = new CustomerMarqueeInfo();
                        customerMarqueeInfo.setAvatarUrl(lookUserInfo.getAvatarUrl());
                        if(totalLookCount>50){
                            customerMarqueeInfo.setCustomerInfo(lookUserInfo.getNickName() + " 上周添加了 " + num + " 个客户");
                        }else if(totalLookCount>40){
                            customerMarqueeInfo.setCustomerInfo(lookUserInfo.getNickName() + " 上周锁定 " + totalLookCount+2 + " 个意向客户");
                        }else if(totalLookCount>20){
                            customerMarqueeInfo.setCustomerInfo(lookUserInfo.getNickName() + " 正在追踪客户中......");
                        }else if(totalLookCount>10){
                            customerMarqueeInfo.setCustomerInfo(lookUserInfo.getNickName() + " 3分钟前添加了 " + totalLookCount + " 个客户");
                        }else if(totalLookCount>0){
                            customerMarqueeInfo.setCustomerInfo(lookUserInfo.getNickName() + " 正在追踪客户中......");
//                            customerMarqueeInfo.setCustomerInfo(lookUserInfo.getNickName() + " 刚刚在人脉广场加了 " + totalLookCount + " 个客户");
                        }else{
                            customerMarqueeInfo.setCustomerInfo(lookUserInfo.getNickName() + " 正在追踪客户中......");
                        }

                        marqueeInfo.add(customerMarqueeInfo);
                    }

                }

            });

            int lookUserArticleStatisInfoSize = lookUserArticleStatisInfos.size();
            if (lookUserArticleStatisInfoSize == 0) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(5));
            } else if (lookUserArticleStatisInfoSize == 1) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(4));
            } else if (lookUserArticleStatisInfoSize == 2) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(3));
            } else if (lookUserArticleStatisInfoSize == 3) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(2));
            } else if (lookUserArticleStatisInfoSize == 4) {
                marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(1));
            }

        } else {

            marqueeInfo.addAll(ToolUtil.getCustomerMarqueeInfoBySpecialSize(5));

        }

        resultMap.put("marqueeInfo", marqueeInfo);

        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 20200519 yl
     * 通过用户id查询品牌推广结算信息
     * @param userId
     * @return
     */
    @PostMapping(value = "/getPromotionSettleByUserId", produces="application/json;charset=UTF-8")
    public RespData getPromotionSettleByUserId(@RequestHeader("userId") String userId) {
        RespData respData = new RespData();
        BrandPromotionSettleInfo brandPromotionSettleInfo = this.brandPromotionSettleInfoService.getPromotionSettleByUserId(userId);
        if (null != brandPromotionSettleInfo){
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setData(brandPromotionSettleInfo);
            respData.setMsg("成功");
            return respData;
        }
        respData.setCode(ReturnCode.SERVER_ERROR);
        respData.setMsg("暂无数据");
        return respData;
    }
    /**
     * 20200519 yl
     * 通过品牌代理人id查询用户付费信息
     * @param userId
     * @return
     */
    @PostMapping(value = "/getPromotionPayByUserId", produces="application/json;charset=UTF-8")
    public RespData getPromotionPayByUserId(@RequestHeader("userId") String userId) {
        RespData respData = new RespData();
        List<BrandPromotionPayUserInfo> brandPromotionPayUserId = this.brandPromotionPayUserInfoService.getPromotionPayByUserId(userId);
        if (CollectionUtils.isNotEmpty(brandPromotionPayUserId)){
            brandPromotionPayUserId.stream().forEach(bpp ->{
                bpp.setOpeningDate(DateUtil.getFormatDate(null,bpp.getCreateTime()));
                bpp.setCreateTime(null);
            });
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setData(brandPromotionPayUserId);
            respData.setMsg("成功");
            return respData;
        }
        respData.setCode(ReturnCode.SERVER_ERROR);
        respData.setMsg("暂无数据");
        return respData;
    }

    /**
     * 20200526 yl
     * 用户领取优惠券
     * @param userId
     * @return
     */
    @PostMapping(value = "/receiveCoupon", produces="application/json;charset=UTF-8")
    public RespData receiveCoupon(@RequestHeader("userId") String userId) {
        UserInfo user = new UserInfo();
        user.setUserId(Integer.valueOf(userId));
        user.setCreateTime(new Date());
        this.redisCacheUtil.setCacheObject(VipInfoHandler.COUPON_PRE + userId, JSON.toJSONString(user), 600L);
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }



}
